package com.example.heizhu.appfuncore.deeplinkdemo;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;

import com.example.heizhu.appfuncore.R;

import java.util.List;

import core.android.deeplinks.deeplinking.AKDeeplink;
import core.android.deeplinks.deeplinking.annotations.DeeplinkQueryParameter;
import core.android.deeplinks.deeplinking.annotations.DeeplinkRoute;
import core.android.tools.AKWebViewUtil;

@DeeplinkRoute("html5")
public class Html5Fragment extends Fragment {

    @DeeplinkQueryParameter("url")
    String mUrl;

    @DeeplinkQueryParameter("referrer")
    String mReferrer;

    WebView webView;
    View loadingTip;//加载中进度条
    AKWebViewUtil webViewUtil;

    public Html5Fragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AKDeeplink.INSTANCE.inject(this);

        Log.d("onCreate-" + getTag(), "mUrl=" + mUrl);
        Log.d("onCreate-" + getTag(), "mReferrer=" + mReferrer);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View contentview = inflater.inflate(R.layout.fragment_html5, container, false);
        initView(contentview);
        return contentview;
    }

    private void initView(View contentview) {
        webView = (WebView) contentview.findViewById(R.id.webview);
        loadingTip = contentview.findViewById(R.id.loading_tip);
        webViewUtil = new AKWebViewUtil(webView, loadingTip);
        webViewUtil.loadUrl(mUrl);
    }

    //配合activiy重写onbackpress调用此方法，实现手机点击返回键只回退webview不关闭activity
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item == null) {
            if (webView != null && webView.canGoBack()) {
                webView.goBack();
                return true;
            } else {
                List<Fragment> fragments = getFragmentManager().getFragments();
                if (fragments.size() > 1) {
                    getFragmentManager().beginTransaction().remove(this).commit();
                } else {
                    //如果是
                    getActivity().finish();
                }
            }
        }
        return super.onOptionsItemSelected(item);//item为null不影响
    }
}
